// import { wxOpt } from './config'
import { posts } from '../service/http'

export function resize (oSelector, selector) {
  let height = document.querySelector(oSelector).offsetHeight
  window.onresize = () => {
    let wrapperEle = document.querySelector(selector || oSelector)
    // console.log(wrapperEle)
    wrapperEle.style.height = height + 'px'
  }
}
export function queryUrl (key) {
  let name, value
  let str = moreCheck(location.href, key) // 取得整个地址栏
  // let str = location.href
  let num = str.indexOf('?')
  str = str.substr(num + 1) // 取得所有参数
  let arr = str.split('&') // 各个参数放到数组里
  let json = {}
  for (let i = 0; i < arr.length; i++) {
    num = arr[i].indexOf('=')
    if (num > 0) {
      name = arr[i].substring(0, num)
      value = arr[i].substr(num + 1)
      json[name] = value
    }
  }
  if (!key) {
    return json
  }
  return json[key]
}
export function moreCheck (query, key) {
  let str = query // 取得整个地址栏
  let num = str.indexOf('?')
  let strArr = []
  str = str.substr(num + 1)
  if (~str.indexOf('?')) {
    strArr = str.split('?')
    if (~strArr[0].indexOf(key + '=')) {
      return moreCheck(strArr[0], key)
    }
    if (~strArr[1].indexOf(key + '=')) {
      return moreCheck(strArr[1], key)
    }
    return moreCheck(str, key)
  }
  return str
}

// 深层copy
export function deepCopy (obj) {
  let res = null
  if (obj === null || obj === undefined) {
    res = obj
    return res
  }
  if (obj.constructor === Object) {
    res = {}
    for (var key in obj) {
      if (obj[key] === null || obj[key] === undefined) {
        res[key] = obj[key]
        continue
      }
      if (obj[key].constructor === Object || obj[key].constructor === Array) {
        res[key] = deepCopy(obj[key])
      } else {
        res[key] = obj[key]
      }
    }
  } else if (obj.constructor === Array) {
    res = []
    obj.forEach((item, index) => {
      if (item === null || item === undefined) {
        res[index] = item
      }
      if (item.constructor === Object || item.constructor === Array) {
        res[index] = deepCopy(item)
      } else {
        res[index] = item
      }
    })
  } else {
    res = obj
  }
  return res
}
/* eslint-disable */
// 两个变量是否相等
export function isObjectEqual(a, b, exclude = []) {
  // null | undefined
  if (a === b) return true

  // not object

  if (!(a instanceof Object) || !(b instanceof Object)) {
    return false
  }
  if (a.constructor !== b.constructor) {
    return false
  }
  for (let key in a) {
    if (a.hasOwnProperty(key) && exclude.indexOf(key) === -1) {
      if (!b.hasOwnProperty(key)) {
        return false
      }
      if (a[key] == b[key]) {
        continue
      }
      if (exclude && exclude.indexOf(key) !== -1) {
        continue
      }

      if (typeof a[key] !== 'object') {
        return false
      }

      if (!isObjectEqual(a[key], b[key])) {
        return false
      }
    }
  }
  for (let key in b) {
    if (b.hasOwnProperty(key) && !a.hasOwnProperty(key)) {
      return false
    }
  }
  return true
}
/* eslint-disable */
export function isIOS() {
  var isIphone = navigator.userAgent.indexOf('iPhone') !== -1
  var isIpad = navigator.userAgent.indexOf('iPad') !== -1
  return isIphone || isIpad
}
// 防抖：某一段时间内只执行一次
// 常用于搜索联想，window-resize
export function debounce(fn, delay) {
  let timer = null
  return function() {
    let args = arguments
    let context = this

    if (timer) {
      clearTimeout(timer)

      timer = setTimeout(function() {
        fn.apply(context, args)
      }, delay)
    } else {
      timer = setTimeout(function() {
        fn.apply(context, args)
      }, delay)
    }
  }
}
// 节流：间隔时间执行
// 常用于鼠标不断点击，滚动事件
export function throttle(fun, delay) {
  let last, deferTimer
  return function(args) {
    let that = this
    let _args = arguments
    let now = +new Date()
    if (last && now < last + delay) {
      clearTimeout(deferTimer)
      deferTimer = setTimeout(function() {
        last = now
        fun.apply(that, _args)
      }, delay)
    } else {
      last = now
      fun.apply(that, _args)
    }
  }
}

export function checkQuery() {
  let currentUrl = location.href
  let queryOid = queryUrl('openid')
  let tenantId = queryUrl('tenantId')
  let labelId = queryUrl('labelId')
  let appid = queryUrl('appid')
  let wechatId = queryUrl('wechatId')
  if (tenantId) {
    localStorage.setItem('tenantId', tenantId)
  }
  if (labelId) {
    localStorage.setItem('labelId', labelId)
  }
  if (appid) {
    sessionStorage.setItem('appid', appid)
  }
  if (wechatId) {
    localStorage.setItem('wechatId', wechatId)
  }
  if (queryOid && queryOid !== 'undefined') {
    localStorage.setItem('openid', queryOid)
  } else {
    localStorage.removeItem('openid')
  }
  return false
}

export function changeUrl(currentUrl) {
  // let currentUrl = location.href
  // 找到 openid= 的位置
  let openidIndex = currentUrl.indexOf('openid=')
  // 找到 openid= 之后 的第一个 & 的位置
  // console.log(openidIndex)
  let openidLastIndex = currentUrl.indexOf('&', openidIndex)
  // 定义新的链接为空
  let shortURL = ''
  if (openidLastIndex > -1) {
    // 如果 openid= 之后还有参数
    let leftStr = currentUrl.substring(0, openidIndex) // 左边截取到openid=的位置
    let rightStr = currentUrl.substring(openidLastIndex + 1) // 右边从openid=之后的第一个&的位置+1 截取后面全部的参数
    shortURL = leftStr + rightStr // 拼接新的链接
  } else {
    shortURL = currentUrl.substring(0, openidIndex - 1)
    // 如果没有后续的参数，就把openid=直到最后截取掉，注意前面需要多截取一位: &或者？
  }
  let timestamp = new Date().valueOf()
  location.href = ~shortURL.indexOf('?')
    ? `${shortURL}&t=${timestamp}`
    : `${shortURL}?t=${timestamp}`
}

export function isPC() {
  var userAgentInfo = navigator.userAgent;
  var Agents = [
    "Android",
    "iPhone",
    "SymbianOS",
    "Windows Phone",
    "iPad",
    "iPod"
  ];
  var flag = true;
  for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false;
      break;
    }
  }
  return flag;
}
// 交换数组元素
export function move(nInd, oInd) {
  if (nInd === oInd) return;
  this.splice(nInd, 0, this.splice(oInd, 1).shift());
}

// 获取字节长度
export function getLength(val) {  
  var str = new String(val);  
  var bytesCount = 0;  
  for (var i = 0 ,n = str.length; i < n; i++) {  
      var c = str.charCodeAt(i);  
      if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {  
          bytesCount += 1;  
      } else {  
          bytesCount += 2;  
      }  
  }  
  return bytesCount;  
} 

/**
 * 生成随机数
 * @param n 生成随机数位数;
 * @returns {string}
 */
export function random (n) {
  const chars = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G',
    'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm',
    'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T',
    't', 'U', 'u', 'V', 'v', 'W', 'w', 'X', 'x', 'Y', 'y', 'Z', 'z'
  ]
  let res = ''
  for (let i = 0; i < n; i++) {
    const id = Math.ceil(Math.random() * 32)
    res += chars[id]
  }
  return res
}

/**
 * 时间戳
 * 格式 20200627140806
 */
export function generateTimestamp () {
  let date = new Date()
  let year = date.getFullYear()
  let month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)
  let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  let hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  let minite = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  let second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return `${year}${month}${day}${hour}${minite}${second}`
}

/**
 * 数据埋点接口
 */
export function actionTrack (data = {}) {
  let nonce = random(16)
  let sign = random(16)
  let timestamp = generateTimestamp()
  let userId = localStorage.getItem('userId')
  let url = `${process.env.VUE_APP_SERVICE_PORTAL}/data/action/track?appId=${process.env.VUE_APP_APPID}&nonce=${nonce}&secretKey=Dmo5wCiT06c6tNnN5L1OFJHlbjRXVKM2&timestamp=${timestamp}&sign=${sign}`
  let _data = {
    action: data.action || 0,
    appid: sessionStorage.getItem('appid'),
    mode: data.mode || 'page',
    nickName: localStorage.getItem('fansNickName') || '访客',
    objId: data.objId || '',
    openid: sessionStorage.getItem('openid') || '',
    page: data.page || '',
    pageId: data.pageId || '',
    tenantId: localStorage.getItem('tenantId')
  }
  if (userId) {
    _data.userId = userId
  }
  posts(url, _data, {}, console.log).then((res) => {
    console.log('actionTrack res', res)
  })
}
